package com.xunk.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.xunk.common.core.enums.ClientEnum;
import com.xunk.common.core.utils.StringUtils;
import com.xunk.common.core.web.domain.AjaxResult;
import com.xunk.common.redis.service.RedisService;
import com.xunk.gateway.service.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * 验证码过滤器
 *
 * @author ruoyi
 */
@Component
public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object> {
    private final static String AUTH_URL = "/oauth/token";

    @Resource(name = "validateCodeService")
    private CodeService validateCodeService;

    @Resource(name = "authCodeService")
    private CodeService authCodeService;

    private static final String BASIC_ = "Basic ";

    public static final String CODE = "code"; // 图片验证码
    public static final String SMS_CODE = "sms_code"; // 短信验证码


    public static final String UUID = "uuid";
    public static final String USERNAME = "username";

    private static final String GRANT_TYPE = "grant_type";

    private static final String REFRESH_TOKEN = "refresh_token";
    private static final String AUTH_CODE_TYPE = "auth_code";

    @Autowired
    RedisService redisService;

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();

            // 非登录请求，不处理
            if (!StringUtils.containsIgnoreCase(request.getURI().getPath(), AUTH_URL)) {
                return chain.filter(exchange);
            }

            // 刷新token请求，不处理
            String grantType = request.getQueryParams().getFirst(GRANT_TYPE);
            if (StringUtils.containsIgnoreCase(request.getURI().getPath(), AUTH_URL) && StringUtils.containsIgnoreCase(grantType, REFRESH_TOKEN)) {
                return chain.filter(exchange);
            }

            // 消息头存在内容，且不存在验证码参数，不处理
            String header = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
            if (StringUtils.isNotEmpty(header) && StringUtils.startsWith(header, BASIC_)
                    && !request.getQueryParams().containsKey(CODE) && !request.getQueryParams().containsKey(UUID)) {
                return chain.filter(exchange);
            }
            String device = request.getHeaders().getFirst("device");
            ClientEnum deviceEnum = ClientEnum.parseClientEnum(device);
            try {
                if (ClientEnum.ANDROID.equals(deviceEnum) || ClientEnum.IPHONE.equals(deviceEnum) || ClientEnum.IPAD.equals(deviceEnum) || ClientEnum.ANDROID_PAD.equals(deviceEnum)) {
                    // 移动端登录(可能密码，可能验证码)
                    if (AUTH_CODE_TYPE.equalsIgnoreCase(grantType)) {
                        // 验证码模式
                        authCodeService.checkCapcha(request.getQueryParams().getFirst(USERNAME), request.getQueryParams().getFirst(SMS_CODE));
                    }
                    // 密码模式直接跳过以后验证
                } else {
                    // web端登录
                    validateCodeService.checkCapcha(request.getQueryParams().getFirst(CODE), request.getQueryParams().getFirst(UUID));
                }
            } catch (Exception e) {
                ServerHttpResponse response = exchange.getResponse();
                response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
                return exchange.getResponse().writeWith(
                        Mono.just(response.bufferFactory().wrap(JSON.toJSONBytes(AjaxResult.error(e.getMessage())))));
            }
            return chain.filter(exchange);
        };
    }
}
